package imp.core.data.songhistory;

import imp.core.basics.ErrorHandler;
import imp.core.basics.IOManager;
import imp.core.basics.date.Date;
import imp.core.data.PathData;
import imp.core.data.configuration.FilePaths;
import imp.core.data.songdata.SongData;

import java.util.ArrayList;


/**
 * The song history data class contains the entire data about played songs.
 * @author Patrick Arnold
 * @since 09.09.2010
 *
 */
public class SongHistoryData implements FilePaths {

	/** The song history list which contains all played songs. */
	public static ArrayList<SongHistoryEntry> songHistory; 

	
	/**
	 * Loads the data and initializes the song history list.
	 * @return Specifies whether loading the data has been successful or not.
	 */
	public static boolean loadData() {
		
		songHistory = new ArrayList<SongHistoryEntry>();
		
		String path = PathData.getProgrampath() + SONGHISTORY;
		String[] file = IOManager.loadFile( path);
		
		if( file == null) {
			return false;
		}
		
		for( int i=0; i < file.length; i++) {
			SongHistoryEntry she = createSongHistoryEntry( file[i], (i+1));
			if( she == null) {
				return false;
			}
		}
		
		
		return true;
		
	}
	
	
	
	/**
	 * Creates a new song history entry out of a simple line from the songhistory.dat. 
	 * @param line A line from the songhistory.dat.
	 * @return The song history object.
	 */
	private static SongHistoryEntry createSongHistoryEntry( String line, int linenumber) {
		
		String[] values = line.split( "::");
		for( int j=0; j < values.length; j++) {
			values[j] = values[j].trim();
		}
		
		try { 
			
    		long id = Long.parseLong( values[0]);
    		String name = values[1];
    		Date date = new Date( values[2], true);
    		int duration = Integer.parseInt( values[3]);
    		double percentage = Double.parseDouble( values[4]);
    		
    		boolean exist = SongData.songExists( id);
    		
    		SongHistoryEntry she = new SongHistoryEntry( id, name, date, duration, percentage, 
    				exist);
    		
    		return she;
    		
		
		} catch( Exception e) {
			String message = "Incorrect line in file songhistory.dat: <br /> &nbsp &nbsp &nbsp "
				+ "Line " + linenumber;
			String location = ErrorHandler.getParserLocation();
			ErrorHandler.error( message, location, e);
			return null;
		}
		
	}
	
	
	
	/**
	 * Adds a song history entry to the list.
	 * @param entry The song history entry.
	 */
	public static void addEntry( SongHistoryEntry entry) {
		
		songHistory.add( entry);
		
		String output = entry.getId() + " :: " + entry.getName() + " :: " 
				+ entry.getDate().getDateAndTime() + "::" + entry.getDuration() + " :: " 
				+ entry.getPercentage();
		
		String[] output_field = { output };
		
		String path = PathData.getProgrampath() + SONGHISTORY;
		IOManager.write( output_field, path, true);
		
	}
	

	
}